<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-menu"></i>{{$route.name}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-dialog title="新增角色" :visible.sync="dialogFormVisible">
                <el-form :model="addForm" :rules="rules" ref="addForm">
                    <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
                        <el-input v-model="addForm.username" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户密码" prop="password" :label-width="formLabelWidth">
                        <el-input v-model="addForm.password" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户角色" prop="roleId" :label-width="formLabelWidth">
                        <el-select v-model="addForm.roleId" placeholder="请选择用户角色">
                            <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="add">确 定</el-button>
                </div>
            </el-dialog>
            <el-dialog title="修改用户" :visible.sync="dialogFormUpdate">
                <el-form :model="upForm">
                    <el-form-item label="用户名" :label-width="formLabelWidth">
                        <el-input v-model="upForm.username" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户密码" :label-width="formLabelWidth">
                        <el-input v-model="upForm.password" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户角色" :label-width="formLabelWidth">
                        <el-select v-model="upForm.roleId" placeholder="请选择用户角色">
                            <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormUpdate = false">取 消</el-button>
                    <el-button type="primary" @click="putUser">确 定</el-button>
                </div>
            </el-dialog>
            <el-input v-model="select_word" placeholder="输入用户名" class="search"></el-input>
            <el-button type="primary" icon="search" @click="search">搜索</el-button>
            <el-button type="primary" @click="beforeAdd">新增用户</el-button>
        </div>
        <div>
            <el-table :data="tableData" border fit style="width: 100%">
                <el-table-column prop="username" label="姓名">
                </el-table-column>
                <el-table-column prop="createTime" label="日期">
                </el-table-column>
                <el-table-column prop="roleId" label="角色" :formatter="formatRole">
                </el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button type="text" size="small" @click="delUser(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="block">
            <el-pagination @current-change="handleCurrentChange" :current-page="page.number+1" layout="total, prev, pager, next, jumper" :total="page.totalElements">
            </el-pagination>
        </div>
    </div>
</template>
<script>
import { users, delUser, addUser, putUser, add_user } from "../../server/getDate.js";
import { mapState, mapActions } from 'vuex'
import { getStore } from '../../utils/local.js'
import { confirm } from '../../utils/local'
export default {
    data() {
        return {
            value: '',
            loading: false,
            dialogTableVisible: false,
            dialogFormVisible: false,
            dialogFormUpdate: false,
            select_word: '',
            upForm: {
                id: 0,
                username: '',
                password: '',
                roleId: '',
            },
            addForm: {
                username: '',
                password: '',
                roleId: ''
            },
            rules: {
                username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
                roleId: [{ required: true, message: '请选择角色', trigger: 'blur' }]
            },
            formLabelWidth: '120px'
        }
    },
    created() {
        this.getUsers()
    },
    computed: mapState({
        page: state => state.Users.result,
        tableData: state => state.Users.result.content,
        roles: state => state.Users.roles,
        user: state => state.Login.user
    }),
    methods: {
        ...mapActions(['saveUsers', 'delUsers', 'updateUser']),
        getUsers() {
            users().then(res => {
                if (res.status === 0) {
                    this.saveUsers(res)
                }
            })
        },
        getRoleName(item, id) {
            if (item.id === id) {
                console.log(item.name)
                return item.name
            }
        },
        handleClick(row) {
            console.log(row)
        },
        formatRole(row, col) {
            let roles = this.roles
            for (let i in roles) {
                if (roles[i].id === row.roleId) {
                    return roles[i].name
                }
            }
            return '未知'
        },
        search() {
            let index = this.page.number + 1
            this.handleCurrentChange(index)
        },
        handleCurrentChange(val) {
            let field = 'username'
            let keyword = this.select_word
            let index = val
            let size = this.page.size
            users({ field, keyword, index, size })
                .then(res => {
                    if (res.status === 0) {
                        this.saveUsers(res)
                    } else {
                        this.$message.error(res.message)
                    }
                }, err => this.$message.error('网络异常'))
        },
        delUser(row) {
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let id = row.id
                let userId = this.user.id
                delUser({ id, userId })
                    .then(res => {
                        if (res.status === 0) {
                            console.log(res)
                            this.delUsers(id)
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });

        },
        add() {
            console.log(this.addForm)
            let userEntity = this.addForm
            let userId = this.user.id
            console.log('userId', userId)
            this.$refs['addForm'].validate((valid) => {
                console.log('valid', valid)
                if (valid) {
                    addUser({ userId, userEntity })
                        .then(res => {
                            if (res.status === 0) {
                                this.dialogFormVisible = false
                                this.$message.info("添加成功")
                                this.add_user(res)
                            } else {
                                this.$message.error(res.message)
                            }
                        }, err => this.$message.error("网络异常"))
                }
            })
        },
        beforeAdd() {
            this.dialogFormVisible = true
            this.addForm = {}
        },
        edit(row) {
            this.dialogFormUpdate = true
            this.upForm.username = row.username
            this.upForm.password = row.password
            this.upForm.roleId = row.roleId
            this.upForm.id = row.id
        },
        putUser() {
            let userEntity = this.upForm
            putUser(userEntity)
                .then(res => {
                    if (res.status === 0) {
                        this.dialogFormUpdate = false
                        this.updateUser(res)
                    } else {
                        this.$message.error(res.message)
                    }
                }, err => this.$message.error(res.message))
        }
    }
}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}

.block {
  text-align: center;
  margin-top: 1%;
}
</style>
